package com.xf.lastmall.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


/**
 * 对dao层进行入参打印
 */
@Slf4j
@Aspect
@Component
public class RepoDaoLogAop {


    /**
     * 以 repo 包下定义的所有请求为切入点
     */
    @Pointcut("execution(public * com.xf.lastmall.order.repo..*(..))")
    public void pointCut() {
    }

    /**
     * 在切点之前织入
     */
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        // 打印请求相关参数
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            log.info("repo dao log aop Class Method:{}.{}, Args:{}", className, methodName, objectMapper.writeValueAsString(filterArgs(joinPoint.getArgs())));
        } catch (JsonProcessingException e) {
            log.error("AOP ERROR...", e);
        }
    }


    /**
     * 过滤无法序列化的参数类型
     *
     * @param args 请求参数
     */
    private Object[] filterArgs(Object[] args) {
        Object[] results = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                //ServletRequest不能序列化，从入参里排除，否则报异常
                continue;
            }
            results[i] = args[i];
        }
        return results;
    }
}